package com.jh.user.service;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.jh.user.util.CommonsUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.TokenUtil;

import com.jh.user.business.AppBrandBusiness;
import com.jh.user.business.ThirdLeveDistributionBusiness;
import com.jh.user.business.UserLoginRegisterBusiness;
import com.jh.user.pojo.AppImageText;
import com.jh.user.pojo.AppSlideshow;
import com.jh.user.pojo.ThirdLevelDistribution;
import com.jh.user.pojo.User;
import com.jh.user.util.Util;


@Controller
@EnableAutoConfiguration
public class AppSystemService {
    @Autowired
    Util util;


    private static final Logger LOG = LoggerFactory.getLogger(AppSystemService.class);
    @Value("${user.appsys.uploadpath}")
    private String realnamePic;

    @Value("${user.appsys.downloadpath}")
    private String downloadPath;

//    @Value("${user.pay.url}")
//    private String payUrl;

    @Autowired
    private UserLoginRegisterBusiness userLoginRegisterBusiness;

    @Autowired
    private ThirdLeveDistributionBusiness thirdLevelBusiness;

    @Autowired
    private AppBrandBusiness appBrandBusiness;


    /**
     * 读取轮播图
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/slideshow/query/brandid")
    public @ResponseBody
    Object downloadAppSlideshow(HttpServletRequest request,
                                @RequestParam(value = "brand_id") long brandid
    ) {
        Map map = new HashMap();
        List<AppSlideshow> AppSlideshows = appBrandBusiness.findAppSlideshowByBrandId(brandid);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESULT, AppSlideshows);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }


    /**
     * 删除轮播图
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/slideshow/delect/id")
    public @ResponseBody
    Object delAppSlideshow(HttpServletRequest request,
                           @RequestParam(value = "id") long id
    ) {
        Map map = new HashMap();
        appBrandBusiness.delAppSlideshowById(id);
        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "成功");
        return map;
    }

    /**
     * 轮播图
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/slideshow/add/{token}")
    public @ResponseBody
    Object addAppSlideshow(HttpServletRequest request,
                           @PathVariable("token") String token,
                           @RequestParam(value = "url") String url,
                           @RequestParam(value = "title") String title,
                           @RequestParam(value = "id", defaultValue = "0", required = false) long id
    ) {
        Map map = new HashMap();
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效");
        }
        try {
            title = URLDecoder.decode(title, "UTF-8");
            url = URLDecoder.decode(url, "UTF-8");

            User user = userLoginRegisterBusiness.queryUserById(userId);
            String src = "slideshow/" + user.getBrandId();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile file = multipartRequest.getFile("image");
            if (file == null) {
                return CommonsUtil.returnError("请添加图片，图片不能为空");
            }
            File dir = new File(realnamePic + src);
            //创建目录
            dir.mkdirs();
            String fileName = file.getOriginalFilename();
            String prefix = fileName.substring(fileName.lastIndexOf("."));
            File dest = new File(realnamePic + src + "/" + System.currentTimeMillis() + prefix);
            file.transferTo(dest);
            AppSlideshow appSlideshow = appBrandBusiness.findAppSlideshowById(id);
            if (appSlideshow == null)
                appSlideshow = new AppSlideshow();
            appSlideshow.setBrandId(user.getBrandId());
            appSlideshow.setTitle(title);
            appSlideshow.setCreateTime(new Date());
            appSlideshow.setUrl(url);
            appSlideshow.setImgurl(downloadPath + src + "/" + dest.getName());
            appSlideshow.setCreateTime(new Date());
            appSlideshow.setUpdatetime(new Date());
            return CommonsUtil.returnSuccess(appBrandBusiness.addAppSlideshow(appSlideshow));
        } catch (Exception e) {
            LOG.error("TerminalInfoService.addAppSlideshow, 轮播图异常=" + e);
            return CommonsUtil.returnError("轮播图失败！");
        }
    }


    /***=======================================图文库================================
     * @throws UnsupportedEncodingException ****/


    /**
     * 删除轮播图
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/imagetext/delect/id")
    public @ResponseBody
    Object delAppText(@RequestParam(value = "id") long id) {
        appBrandBusiness.delAppImageTextById(id);
        return CommonsUtil.returnSuccess("");
    }

    /****
     * 图文库=文
     *
     * ***/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/imagetext/add/txt/{token}")
    public @ResponseBody
    Object addAppText(@PathVariable("token") String token,
                      @RequestParam(value = "content") String content,
                      @RequestParam(value = "title") String title,
                      @RequestParam(value = "remarks", defaultValue = "", required = false) String remarks,
                      @RequestParam(value = "remarks1", defaultValue = "", required = false) String remarks1,
                      @RequestParam(value = "id", defaultValue = "0", required = false) long id) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效");
        }
        try {
            title = URLDecoder.decode(title, "UTF-8");

            User user = userLoginRegisterBusiness.queryUserById(userId);
            AppImageText appImageText = appBrandBusiness.findAppImageTextById(id);
            if (appImageText == null) {
                appImageText = new AppImageText();
                appImageText.setRemarks(remarks);
                appImageText.setRemarks1(remarks1);
            } else {
                appImageText.setRemarks(StringUtils.isBlank(remarks) ? appImageText.getRemarks() : remarks);
                appImageText.setRemarks1(StringUtils.isBlank(remarks1) ? appImageText.getRemarks1() : remarks1);
            }
            appImageText.setBrandId(user.getBrandId());
            appImageText.setTitle(title);
            appImageText.setContent(content);
            appImageText.setCreateTime(new Date());
            appImageText.setUpdatetime(new Date());
            return CommonsUtil.returnSuccess(appBrandBusiness.addAppImageText(appImageText));
        } catch (Exception e) {
            LOG.error("AppSystemService.addAppText,图文库=文异常=" + e);
            return CommonsUtil.returnError("图文库=文失败！");
        }
    }

    /****
     * 图文库=图
     *
     * ***/
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/imagetext/add/image/{token}")
    public @ResponseBody
    Object addAppImage(HttpServletRequest request,
                       @PathVariable("token") String token,
                       @RequestParam(value = "id", defaultValue = "0", required = false) long id) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效");
        }
        try {
            User user = userLoginRegisterBusiness.queryUserById(userId);
            String src = "imagetext/" + user.getBrandId();
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            List<MultipartFile> files = multipartRequest.getFiles("image");
            if (files.isEmpty() || files.size() == 0) {
                return CommonsUtil.returnError("请添加图片，图片不能为空！");
            }
            File dir = new File(realnamePic + src);
            //创建目录
            dir.mkdirs();
            int i = 1;
            String imgurls = "";
            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    String prefix = fileName.substring(fileName.lastIndexOf("."));
                    i++;
                    File dest = new File(realnamePic + src + "/" + System.currentTimeMillis() + i + prefix);
                    imgurls += downloadPath + src + "/" + dest.getName() + ",";
                    file.transferTo(dest);

                }
            }
            AppImageText appImageText = null;
            if (id == 0) {
                List<AppImageText> appImageTexts = appBrandBusiness.findAppImageTextByBrandId(user.getBrandId());
                if (appImageTexts != null && appImageTexts.size() > 0) {
                    appImageText = appImageTexts.get(0);
                }

            } else {
                appImageText = appBrandBusiness.findAppImageTextById(id);
            }
            if (appImageText == null) {
                return CommonsUtil.returnError("失败");
            }
            appImageText.setImgurl(imgurls.substring(0, imgurls.length() - 1));
            appImageText.setUpdatetime(new Date());
            return CommonsUtil.returnSuccess(appBrandBusiness.addAppImageText(appImageText));
        }catch (Exception e){
            return CommonsUtil.returnError("");
        }
    }

    /**
     * 读取图文库
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/imagetext/query/brandid")
    public @ResponseBody Object downloadAppImageText(@RequestParam(value = "brand_id") long brandid) {
        try {
            List<AppImageText> appImageTexts = appBrandBusiness.findAppImageTextByBrandId(brandid);
            List<Map> filepaths = new ArrayList<Map>();
            for (AppImageText appImageText : appImageTexts) {
                Map appImageText_ = new HashMap();
                appImageText_.put("id", appImageText.getId());
                appImageText_.put("title", appImageText.getTitle());
                appImageText_.put("content", appImageText.getContent());
                appImageText_.put("remarks", appImageText.getRemarks());
                appImageText_.put("remarks1", appImageText.getRemarks1());
                appImageText_.put("img_url", StringUtils.isNotBlank(appImageText.getImgurl()) ? appImageText.getImgurl().split(",") : "");
                appImageText_.put("brand_id", appImageText.getBrandId());
                appImageText_.put("create_time", appImageText.getCreateTime());
                appImageText_.put("update_time", appImageText.getUpdatetime());
                filepaths.add(appImageText_);
            }
            return CommonsUtil.returnSuccess(filepaths);
        }catch (Exception e){
            LOG.error("AppSystemService.downloadAppImageText，读取图文库异常=" + e);
            return CommonsUtil.returnError("读取图文库失败！");
        }
    }
    /****===============================店铺管理=================================***/

    /**
     * 读取信息
     */
    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/user/app/usersys/query/{token}")
    public @ResponseBody Object downloadAppUsersys(@PathVariable("token") String token) {
        long userId;
        try {
            userId = TokenUtil.getUserId(token);
        } catch (Exception e) {
            return CommonsUtil.returnError("token无效");
        }
        try {
            User user = userLoginRegisterBusiness.queryUserById(userId);
            /***
             * 1、获取当前用户所在贴牌的等级信息
             * 2、获取用户的直推userIDs
             * 3、获取用户的所有间推用户Ids
             * 4、循环赋予各级别的直推间推个数
             * 5、判断未实名未实名人数，已实名人数
             * **/
            List<ThirdLevelDistribution> thirdLevelDistributions = thirdLevelBusiness.getAllThirdLevelPrd(user.getBrandId());
            Long[] preids = {user.getId()};
            Long[] sonIds = userLoginRegisterBusiness.queryUserIdBypreUserIds(preids);
            String grandsonIds = "";
//            Long[] preuids = sonIds;
//            if (sonIds != null && sonIds.length != 0 && sonIds[0] > 0) {
//                for (int i = 0; true; i++) {
//                    Long[] pids = userLoginRegisterBusiness.queryUserIdBypreUserIds(preuids);
//                    if (pids != null && pids.length > 0 && pids[0] > 0) {
//                        preuids = new Long[pids.length];
//                        preuids = pids;
//                        for (Long uid : pids) {
//                            grandsonIds += uid + ",";
//                        }
//                    } else {
//                        break;
//                    }
//                }
//            }

//            if (grandsonIds.length() > 0) {
//                grandsonIds = grandsonIds.substring(0, grandsonIds.length() - 1);
//                String[] str1 = grandsonIds.split(",");
//                preuids = new Long[str1.length];
//                for (int j = 0; j < str1.length; j++) {
//                    preuids[j] = Long.valueOf(str1[j]);
//                }
//            } else {
//                preuids = null;
//            }
            /****
             *管理等级
             * ***/
            List<Map> gradeList = new ArrayList<Map>();
            if (thirdLevelDistributions != null)
                for (ThirdLevelDistribution thirdLevelDistribution : thirdLevelDistributions) {
                    Map grade = new HashMap();
                    grade.put("grade", thirdLevelDistribution.getGrade());
                    grade.put("name", thirdLevelDistribution.getName());
                    grade.put("url", "");
                    if (sonIds != null && sonIds.length > 0 && sonIds[0] > 0) {
                        Long[] GradesonIds = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(thirdLevelDistribution.getGrade() + "", sonIds);
                        if (GradesonIds != null && GradesonIds.length > 0 && GradesonIds[0] > 0) {
                            grade.put("GradesonIds", GradesonIds.length);
                        } else {
                            grade.put("GradesonIds", 0);
                        }

                    } else {
                        grade.put("GradesonIds", 0);
                    }
//                    if (preuids != null && preuids.length > 0 && preuids[0] > 0) {
//                        Long[] Gradepreuids = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(thirdLevelDistribution.getGrade() + "", preuids);
//                        if (Gradepreuids != null && Gradepreuids.length > 0 && Gradepreuids[0] > 0) {
//                            grade.put("Gradepreuids", Gradepreuids.length);
//                        } else {
//                            grade.put("Gradepreuids", 0);
//                        }
//
//                    } else {
//                        grade.put("Gradepreuids", 0);//间推人
//                    }
                    gradeList.add(grade);
                }
            {
                Map grade = new HashMap();
                grade.put("grade", 0);
                grade.put("name", "普通用户");
                grade.put("url", "");
                if (sonIds != null & sonIds.length > 0 && sonIds[0] > 0) {
                    Long[] GradesonIds = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(0 + "", sonIds);
                    if (GradesonIds != null && GradesonIds.length > 0 && GradesonIds[0] > 0) {
                        grade.put("GradesonIds", GradesonIds.length);
                    } else {
                        grade.put("GradesonIds", 0);//直推人
                    }

                } else {
                    grade.put("GradesonIds", 0);
                }
//                if (preuids != null && preuids.length > 0 && preuids[0] > 0) {
//                    Long[] Gradepreuids = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndGrade(0 + "", preuids);
//                    if (Gradepreuids != null && Gradepreuids.length > 0 && Gradepreuids[0] > 0) {
//                        grade.put("Gradepreuids", Gradepreuids.length);
//                    } else {
//                        grade.put("Gradepreuids", 0);
//                    }
//
//                } else {
//                    grade.put("Gradepreuids", 0);
//                }

                gradeList.add(grade);
            }
            String talluid = "";
            if (sonIds != null) {
                for (Long uid : sonIds) {
                    talluid += uid + ",";
                }
            }
//            if (preuids != null) {
//                for (Long uid : preuids) {
//                    talluid += uid + ",";
//                }
//            }
            Long[] talluidl = {};
            if (talluid.length() > 0) {
                talluid = talluid.substring(0, talluid.length() - 1);
                String[] str1 = talluid.split(",");
                talluidl = new Long[str1.length];
                for (int j = 0; j < str1.length; j++) {
                    talluidl[j] = Long.valueOf(str1[j]);
                }
            }
            Map truefalse = new HashMap();
            Long[] truenum = null;
            if (talluidl != null && talluidl.length > 0 && talluidl[0] > 0) {
                truenum = userLoginRegisterBusiness.queryUserIdBypreUserIdsAndrealnameStatus("1", talluidl);
            }
            truefalse.put("truenum", truenum == null ? 0 : truenum.length);//实名的
            truefalse.put("falsenum", truenum == null ? talluidl.length : talluidl.length - truenum.length);//未实名的
            truefalse.put("thirdLevelDistribution", gradeList);
            return CommonsUtil.returnSuccess(truefalse);
        }catch (Exception e){
            LOG.error("AppSystemService.downloadAppUsersys, 读取信息异常=" + e);
            return CommonsUtil.returnError("读取信息失败！");
        }
    }


}
